<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { deptApi } from '@/api/dept'

// 搜索条件
const searchForm = reactive({
  deptName: '',
  status: ''
})

// 部门列表数据
const deptData = ref([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: 'total, prev, pager, next, jumper, sizes'
})

// 加载状态
const loading = ref(false)

// 对话框相关状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEditMode = ref(false)
const editingId = ref(null)

// 表单数据
const formData = reactive({
  name: '',
  status: 1
})

// 获取部门列表
  const getDeptList = async () => {
    loading.value = true
    try {
      // 构建查询参数，根据后端接口要求调整参数名称和类型
      const params = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize,
        name: searchForm.deptName || undefined,
        status: searchForm.status ? parseInt(searchForm.status) : undefined
      }
      
      console.log('准备请求部门列表，参数:', params)
      const response = await deptApi.getDeptList(params)
      
      // 直接访问响应对象的data属性
      const res = response.data
      console.log('处理后的响应数据:', res)
      
      // 根据后端Result类格式处理响应
      // 后端返回格式: { ...Result对象, data: PageResult对象 }
      // PageResult对象格式: { total: 总数, rows: 数据列表 }
      if (res.code === 1 || res.code === 200 || res.success === true) {
        // 后端成功响应
        if (res.data && typeof res.data === 'object') {
          const pageResult = res.data
          // 明确使用rows字段作为数据列表，total作为总数
          deptData.value = pageResult.rows || []
          pagination.total = pageResult.total || 0
          console.log('获取部门列表成功，数据量:', deptData.value.length, '总数:', pagination.total)
        } else {
          console.warn('响应数据格式不符合PageResult结构:', res.data)
          deptData.value = []
          pagination.total = 0
          ElMessage.warning('数据格式异常，请检查后端接口')
        }
      } else {
        const errorMsg = res.msg || res.message || '获取部门列表失败'
        console.error('获取部门列表失败，错误信息:', errorMsg)
        ElMessage.error(errorMsg)
      }
    } catch (error) {
      console.error('获取部门列表异常:', {
        message: error.message,
        stack: error.stack,
        response: error.response
      })
      
      // 根据不同的错误类型提供更具体的提示
      if (error.message.includes('timeout')) {
        ElMessage.error('请求超时，请检查网络连接或后端服务是否正常')
      } else if (error.message.includes('Network')) {
        ElMessage.error('网络错误，请检查网络连接')
      } else if (error.response?.status === 404) {
        ElMessage.error('接口不存在，请检查后端服务是否正常运行')
      } else if (error.response?.status === 500) {
        // 尝试获取后端返回的详细错误信息
        const errorDetail = error.response.data?.msg || error.response.data?.message || '服务器内部错误'
        ElMessage.error(`服务器错误: ${errorDetail}`)
        console.error('后端错误详情:', error.response.data)
      } else {
        ElMessage.error('获取部门列表失败，请稍后重试')
      }
    } finally {
      loading.value = false
    }
  }

// 搜索方法
const handleSearch = () => {
  pagination.currentPage = 1
  getDeptList()
}

// 清空搜索条件
const handleClear = () => {
  searchForm.deptName = ''
  searchForm.status = ''
  handleSearch()
}

// 重置表单
const resetForm = () => {
  formData.name = ''
  formData.status = 1
  editingId.value = null
}

// 打开添加部门对话框
const handleAdd = () => {
  isEditMode.value = false
  dialogTitle.value = '添加部门'
  resetForm()
  dialogVisible.value = true
}

// 打开修改部门对话框
const handleEdit = async (row) => {
  try {
    // 先获取部门详情
    console.log('获取部门详情，ID:', row.id)
    const response = await deptApi.getDeptDetail(row.id)
    const res = response.data
    
    if (res.code === 1 || res.code === 200 || res.success === true) {
      isEditMode.value = true
      dialogTitle.value = '修改部门'
      editingId.value = row.id
      
      // 填充表单数据
      const deptData = res.data
      formData.name = deptData.name || ''
      formData.status = deptData.status || 1
      
      dialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取部门详情失败')
    }
  } catch (error) {
    console.error('获取部门详情异常:', error)
    ElMessage.error('获取部门详情失败，请稍后重试')
  }
}

// 删除部门
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除部门「${row.name}」吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    console.log('准备删除部门ID:', row.id)
    const response = await deptApi.deleteDept(row.id)
    
    // 处理响应，与getDeptList方法保持一致的响应处理逻辑
    const res = response.data
    console.log('删除部门响应:', res)
    
    if (res.code === 1 || res.code === 200 || res.success === true) {
      ElMessage.success('删除成功')
      getDeptList() // 重新获取部门列表
    } else {
      const errorMsg = res.msg || res.message || '删除失败'
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除部门异常:', {
        message: error.message,
        response: error.response
      })
      
      if (error.response?.status === 500) {
        const errorDetail = error.response.data?.msg || '服务器错误'
        ElMessage.error(`删除失败: ${errorDetail}`)
      } else {
        ElMessage.error('删除失败，请稍后重试')
      }
    }
  }
}

// 页码改变
const handleCurrentChange = (current) => {
  pagination.currentPage = current
  getDeptList()
}

// 每页条数改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  getDeptList()
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!formData.name.trim()) {
    ElMessage.warning('请输入部门名称')
    return
  }
  
  try {
    loading.value = true
    let response
    
    // 准备提交数据
    const submitData = {
      id: isEditMode.value ? editingId.value : undefined,
      name: formData.name.trim(),
      status: formData.status
    }
    
    console.log('准备提交数据:', submitData)
    
    // 根据模式调用不同的API
    if (isEditMode.value) {
      response = await deptApi.updateDept(submitData)
    } else {
      response = await deptApi.addDept(submitData)
    }
    
    const res = response.data
    console.log('提交响应:', res)
    
    if (res.code === 1 || res.code === 200 || res.success === true) {
      ElMessage.success(isEditMode.value ? '修改成功' : '添加成功')
      dialogVisible.value = false
      getDeptList() // 重新获取部门列表
    } else {
      const errorMsg = res.msg || res.message || (isEditMode.value ? '修改失败' : '添加失败')
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    console.error('提交异常:', error)
    const errorDetail = error.response?.data?.msg || '服务器错误'
    ElMessage.error(`${isEditMode.value ? '修改' : '添加'}失败: ${errorDetail}`)
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 页面加载时获取部门列表
onMounted(() => {
  getDeptList()
})
</script>

<template>
  <div class="dept-management">
    
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-row :gutter="12">
        <el-col :span="6">
          <el-form-item label="部门名称:">
            <el-input 
              v-model="searchForm.deptName" 
              placeholder="请输入部门名称"
              clearable
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态:">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择"
              clearable
              style="width: 100%"
            >
              <el-option label="正常" value="1" />
              <el-option label="停用" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" :offset="8" class="button-col">
          <el-button type="primary" @click="handleSearch" style="margin-right: 8px;">搜索</el-button>
          <el-button @click="handleClear">清空</el-button>
        </el-col>
      </el-row>
      
      <!-- 分隔符 -->
      <div class="divider"></div>
      
      <!-- 添加部门按钮 -->
      <div class="action-area">
        <el-button type="primary" @click="handleAdd">添加部门</el-button>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <el-table 
      :data="deptData" 
      style="width: 100%"
      stripe
      border
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <el-table-column prop="id" label="序号" width="80" align="center" />
      <el-table-column prop="name" label="部门名称" align="center" />
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <span :style="{ color: scope.row.status === 0 ? 'red' : 'inherit' }">
            {{ scope.row.status === 0 ? '停用' : '正常' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最后修改时间" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button 
            type="primary" 
            link 
            @click="handleEdit(scope.row)"
            style="margin-right: 8px;"
          >
            修改
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页控件 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="pagination.pageSizes"
        layout="total, prev, pager, next, jumper, sizes"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 添加/修改部门对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleClose"
    >
      <el-form label-width="80px" :model="formData" :label-position="'top'">
        <el-form-item label="部门名称" required>
          <el-input
            v-model="formData.name"
            placeholder="请输入部门名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="状态" required>
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="正常" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">
            {{ isEditMode ? '确定修改' : '确定添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.dept-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.search-area {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
}

.el-form-item {
  margin-bottom: 0;
}

/* 调整按钮列样式，确保清空按钮到右边框的距离与部门名称到左边框的距离一致 */
.button-col {
  padding-right: 0;
  display: flex;
  justify-content: flex-end;
}

.action-area {
  margin-top: 15px;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
  width: 100%;
  display: flex;
  justify-content: flex-end;
}

/* 分隔线样式 */
.divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 15px 0;
}

/* 对话框表单样式 */
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog .el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

/* 调整选择框样式 */
:deep(.el-dialog .el-select) {
  width: 100%;
}
</style>
